<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
</style>
<body>

<p><button onclick="myMove()">单击我</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>

<script>
function myMove() {
  var elem = document.getElementById("animate");   
  var pos = 0;
  var id = setInterval(frame, 10);
  var flag = true;
  function frame() {
    if (pos == 350) {
    //   clearInterval(id);
        flag = false;
    } 
     if(flag==true){
      pos++; 
      elem.style.top = pos + "px"; 
      elem.style.left = pos + "px"; 
    }else {
      pos--;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    
      // 添加检查是否回到原点
      if (pos == 0) {
        flag = true;
      }
    }
  }
}
</script>

</body>
</html>
